package com.boruiimage.demo.controller;
import com.boruiimage.demo.doMain.Result;
import com.boruiimage.demo.doMain.memberuser;
import com.boruiimage.demo.mapperDao.registerMapperDao;
import com.boruiimage.demo.repository.filePartDao;
import com.boruiimage.demo.repository.imgInfoDao;
import com.boruiimage.demo.repository.registerMemberUserDao;
import com.boruiimage.demo.utils.AES;
import com.boruiimage.demo.utils.JsonUtils;
import com.boruiimage.demo.utils.checkImages;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
public class fileHand {
    @Autowired
    filePartDao fpd;
    //图片上传
    @RequestMapping("/sd")
    public Result show( MultipartFile file, HttpServletRequest request,
                       @RequestParam(value = "userName") String userName, HttpServletResponse response,
                       @RequestParam(value = "imgType")String imgType) throws JpegProcessingException, IOException {
        String filename = file.getOriginalFilename();
        System.out.println(filename + "文件名称");
        Random rd = new Random();
        Result rs = new Result();
        int i = rd.nextInt(1000);
        String name = i + filename.split("\\.")[0];
        //获取图片扩展名
        String ext = filename.substring(filename.lastIndexOf(".") + 1);
        //生成图片名称
        String imgName = "name";//自己写的一个获取字符串的方法作为图片名称
        //生成图片的存放在服务器的路径
        String path = "/images/" + name + "." + ext;
        //获取服务器的绝对路径进行保存图片
        //String url = request.getSession().getServletContext().getRealPath("")+path;
        String url = "/opt/bigdata_px_api/images/" + name + "." + ext;//;服务器地址
        //String url="E:\\images\\"+name + "." + ext;//本地服务器地址
        System.out.println("url" + url);
        String pathName = "http://52borui.cn:8081/" + name + "." + ext;
        String imgNames=name + "." + ext;
        //图片上传
        try {
            InputStream in = file.getInputStream();
            OutputStream out = new FileOutputStream(new File(url));
            byte[] b = new byte[1024];
            int len;
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
            in.close();
            out.close();
            File files = new File("/opt/bigdata_px_api/images/" + imgNames);
            System.out.println(imgNames);
            if (files.exists()) {
                Result rss=checkImages.checkImage(imgNames);//鉴定图片
                rs.setMsg(rss.getMsg());
                rs.setMap(rss.getMap());
                rs.setImgName(imgNames);
            } else {
                rs.setCode(3);//图片上传失败
            }
        } catch (IOException e) {
            //rs.setCode(0);
            throw e;
        }
        //编写图片上传的业务逻辑方法
        //获取图片名称
        if(userName!=null){//判断是否登录
            rs.setCode(4);
        }
        //情况判定 1用户是否是会员，2 用户会员次是否已用完 3，不是会员
        memberuser memberuser=fpd.us(AES.encrypt(userName));//判断该用户是否是会员
        System.out.println(imgType);
        if(memberuser!=null){
           if(imgType.equals("系统鉴定")){
               if(rmud.meSleect(AES.encrypt(userName))==0){//查询该用户的系统次数是否还有
                   rs.setResult("该用户系统服务鉴定次数已经用完");//如果该用户是会员并且次数已经用完直接使用扫码支付
               }else {
                   //按照开通时间去扣除使用次数
                   String imgDetil="http://52borui.cn:8081/" +imgNames;
                  try{
                      Result rse=rmud.SelectBydata(AES.encrypt(userName),4,imgNames,imgDetil,rs.getMsg(),null);
                  }catch (Exception e){
                      throw e;
                  }
                   rs.setResult("该用户还有系统鉴定次数");//如果该用户是会员系统鉴定次数没有用完 请求扣除次数接口扣除该用户的系统鉴定次数
               }
           }else if(imgType.equals("专家鉴定")){
               if(rmud.meSleectPerson(AES.encrypt(userName))==0){//查询该用户的专家次数是否还有
                   rs.setResult("该用户专家服务鉴定次数已经用完");//如果该用户是会员并且次数已经用完直接使用扫码支付
               }else if(rmud.meSelectByUsername(AES.encrypt(userName)).equals("1")){
                   rs.setResult("该用户只开通了金牌会员");//说明该用户只开通了金牌会员
               }else {
                   //按照开通时间去扣除使用次数
                   String imgDetil="http://52borui.cn:8081/" +imgNames;
                   try{
                       Result rse=rmud.SelectBydata(AES.encrypt(userName),5,imgNames,imgDetil,rs.getMsg(),null);
                   }catch (Exception e){
                       throw e;
                   }
                   rs.setResult("该用户还有专家鉴定次数");//如果还用户是会员专家鉴定次数没有用完 请求扣除次数接口扣除该用户的专家鉴定次数
               }
           }
        }else{
            if(imgType.equals("系统鉴定")){
                rs.setResult("该用户不是系统鉴定会员");
            }else if(imgType.equals("专家鉴定")){
                rs.setResult("该用户不是专家鉴定会员");
            }

        }
          rs.setCourse(imgType);
        return rs;
    }


    @Autowired
    registerMemberUserDao rmuds;
    @RequestMapping("/showPersonTime")
    public Result showPersonTime(@RequestParam(value = "userName")String userName){
        return rmuds.SelectByifo(AES.encrypt(userName));
    }

   @Autowired
   registerMemberUserDao rmud;
    imgInfoDao ifo;
    //app端
    @RequestMapping("/isUpdate")
    public Result showsApp(@RequestBody Map<String,String>maps) throws JpegProcessingException, IOException {
        Result rs = new Result();
        String image=maps.get("image");

        System.out.println(maps.get("code"));
        //查询该通湖是不是会员是的话返回code0 msg结果
         memberuser us = rmud.us(maps.get("userName"));
        String pathName = "http://52borui.cn:8081/" +image;
        if(maps.get("code").equals("5")){//如果是人工服务
            rs=rmud.SelectBydataTong(maps.get("userName"));
        }
        if(us==null){
             if(maps.get("code").equals("4")){//0 不是会员但是图片鉴定成功  3表示图片格式有问题
                 try{
                     rs=checkImages.checkImage(image);
                     rs.setCode(0);
                 }catch (Exception e){
                     rs.setCode(3);
                     return rs;
                 }
             }/*else if(maps.get("code").equals("5")){
                 try{
                    //rs=checkImages.checkImage(image);
                     rs.setCode(0);
                 }catch (Exception e){
                    // rs.setCode(3);
                     return rs;
                 }
             }*/else if(maps.get("code").equals("6")){
                 try{
                     rs=checkImages.checkImage(image);
                     rs.setCode(1);

                 }catch (Exception e){
                     rs.setCode(3);
                     return rs;
                 }
             }
         }else if(us!=null){
             //查询用户如果是会员查询有没有鉴定次数  按照开通日期查询搜索

             if(maps.get("code").equals("4")){
                  Integer meus= rmud.meSleect(maps.get("userName"));
               if(meus>0){//系统次数
                  try{
                      //如果会员有次数返回code 2 没有返回1
                      rs=checkImages.checkImage(image);
                      rs.setCode(2);

                  }catch (Exception e){
                      rs.setCode(3);
                  }
                   return  rs;
               }else{
                   try{
                       rs=checkImages.checkImage(image);
                       rs.setCode(1);

                   }catch (Exception e){
                       rs.setCode(3);
                   }
                   return  rs;
               }
             }/*else if(maps.get("code").equals("5")){//人工次数
                memberuser meus= rmud.meSleectPerson(maps.get("userName"));
                System.out.println(meus.getPersonCount()+"ssssss");
                 if(meus.getPersonCount()>0){
                    try{
                       // rs=checkImages.checkImage(image);
                        rs.setCode(2);
                    }catch (Exception e){
                       // rs.setCode(3);
                    }
                     return  rs;
                 }else{
                     try{
                         //rs=checkImages.checkImage(image);
                         rs.setCode(1);
                     }catch (Exception e){
                         //rs.setCode(3);
                     }
                     return  rs;
                 }
             }*/else if(maps.get("code").equals("6")){

                     try{
                         rs=checkImages.checkImage(image);
                         rs.setCode(1);

                     }catch (Exception e)    {
                           rs.setCode(3);
                     }
                 return rs;
             }
         }
         System.out.println(rs);
        return  rs;
    }


    @Autowired
    registerMemberUserDao rmudu;
    @RequestMapping(value = {"/addPicture"}, method = RequestMethod.POST)
    public Result addPicture(@RequestParam(value = "phone_code") String phone_code, @RequestParam MultipartFile file) throws IOException {
            Map<String, String> map = JsonUtils.deserialize(phone_code, new TypeToken<Map<String, String>>(){}.getType());
             Result rs=new Result();
             System.out.println(map.get("phone")+"------------");
             System.out.println(map.get("code")+"---------+++++++---");
        if (!file.isEmpty()) {
            System.out.println("addPicture-phone: " + map.get("phone"));
            Random rd=new Random();
            int i=rd.nextInt(1000);
            String imgName = i+file.getOriginalFilename();
            String directory_picture = "/opt/bigdata_px_api/images";
            String path = directory_picture + "/" + imgName;
            File directory = new File(directory_picture);
            if (!directory.exists()) {
                try {
                    directory.mkdirs();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(path)));
            System.out.println(file.getName());
            out.write(file.getBytes());
            out.flush();
            out.close();
            File files = new File("/opt/bigdata_px_api/images/" + imgName);
            if(files.exists()){
              if(map.get("code").equals("5")){
                  Result result = rs=rmudu.SelectBydataTong(AES.encrypt(map.get("phone")));
                  rs.setId(result.getCode());
                  rs.setMsg(imgName);
                  rs.setCode(1);
              }else if(map.get("code").equals("4")){
                  rs.setMsg(imgName);
                  rs.setCode(1);
              }
            }else {
                rs.setCode(0);
            }
        }
       return rs;
    }
}